﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPCAutomatic.DAL
{
    internal class HFconst
    {
        private readonly string    _connectionString;

        public HFconst(string connectionString)
        {
            _connectionString = connectionString;
            InitializedHFconstDatabase();
        }

        private void InitializedHFconstDatabase()
        {
            try
            {
                using (var connection = new SQLiteConnection(_connectionString))
                {
                    connection.Open();
                    // 检查Initialization表是否存在
                    string checkTableSql = "SELECT name FROM sqlite_master WHERE type='table' AND name='Initialization'";
                    using (var checkTableCmd = new SQLiteCommand(checkTableSql, connection))
                    {
                        var result = checkTableCmd.ExecuteScalar();
                        if (result == null)
                        {
                            // 表不存在则创建
                            string createTableSql = @"      
CREATE TABLE [Initialization](
    [ID] INTEGER PRIMARY KEY AUTOINCREMENT, 
    [寄存器] TEXT DEFAULT '02', 
    [寄存器值] TEXT)";
                            using (var createTableCmd = new SQLiteCommand(createTableSql, connection))
                            {
                                createTableCmd.ExecuteNonQuery();
                            }
                            // 插入默认行
                            string insertSql = "INSERT INTO [Initialization] ([寄存器], [寄存器值]) VALUES ('02', '')";
                            using (var insertCmd = new SQLiteCommand(insertSql, connection))
                            {
                                insertCmd.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("初始化HFconst数据库时出错", ex);
            }
        }

        public string GetInitializationHFconstValue() 
        {
            try
            {
                using (var connection = new SQLiteConnection(_connectionString))
                {
                    connection.Open();
                    // 查询保存的值
                    string selectSql = "SELECT [寄存器值] FROM [Initialization] WHERE [寄存器] = '02' LIMIT 1";
                    using (var selectCmd = new SQLiteCommand(selectSql, connection))
                    {
                        return selectCmd.ExecuteScalar()?.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("获取HFconst初始化值时出错", ex);
            }
        }

        public void SaveInitializationHFconstValue(string value)
        {
            try
            {
                using (var connection = new SQLiteConnection(_connectionString))
                {
                    connection.Open();
                    // 更新或插入记录
                    string upsertSql = @"      
INSERT OR REPLACE INTO [Initialization] ([ID], [寄存器], [寄存器值])      
SELECT 
    (SELECT ID FROM [Initialization] WHERE [寄存器] = '02' LIMIT 1),
    '02',
    @寄存器值      
WHERE NOT EXISTS (SELECT 1 FROM [Initialization] WHERE [寄存器] = '02');      
UPDATE [Initialization] SET [寄存器值] = @寄存器值 WHERE [寄存器] = '02'";
                    using (var command = new SQLiteCommand(upsertSql, connection))
                    {
                        command.Parameters.AddWithValue("@寄存器值", value);
                        command.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("保存HFconst初始化值时出错", ex);
            }
        }
    }
}
